package com.touchapk.core;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description
 * @author yangkeyun
 * @email coyun@qq.com
 * @date 2016年8月23日
 * @version V1.0
 */
public class AdbMonitor {
	
	
	private final static long SLEEP_TIME=1800;
	
	public static void monitor() {
		
		new Thread(new Runnable() {
			
			public void run() {
				while (true) {
					try {
						
					List<String> activeUdids=Events.adbService.getConnectedDevicesUdid();
					
					listToMap(activeUdids);
					
					} catch (Exception e) {
						openWinExe();
					}
					
					try {
						Thread.sleep(SLEEP_TIME);
					} catch (Exception e) {}
					
				}
			}
		}).start();
		
	}
	
	
	public static void openWinExe() {
		
		Runtime rn = Runtime.getRuntime();
		Process p = null;
		try {
			String command = "adb start-server";
			p = rn.exec(command);
		} catch (Exception e) {}
		
	}
	
	
	public static void listToMap(List<String> activeUdids){
		
		Map<String,String> tmp=new HashMap<String,String>();
		
		for(String udid:activeUdids){
			
			tmp.put(udid, null);
			
			if(!Events.activeUdids.containsKey(udid)){
				
				try {
					
					Map map=Events.adbService.getPropertiesForDevice(udid);
					
					String manu="";
					String name="";
					
					if(map.containsKey("ro.product.manufacturer")){
						manu=map.get("ro.product.manufacturer").toString();
					}
					
					if(map.containsKey("ro.product.model")){
						name=map.get("ro.product.model").toString();
					}
					
					String str="";
					
					if(!"".equals(manu)&&!"".equals(name)){
						str=manu+"("+name+")";
					}else if(!"".equals(manu)&&"".equals(name)){
						str=manu;
					}else if("".equals(manu)&&!"".equals(name)){
						str=name;
					}else{
						str=udid;
					}
					
					Events.activeUdids.put(udid, str);
					
				} catch (Exception e) {}
			}
		}
		
		for(String k:Events.activeUdids.keySet()){
			if(!tmp.containsKey(k)){
				Events.activeUdids.remove(k);
			}
		}
		
	}
}
